package com.eims.sls_app.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import bls.juejin.cn.R;

import com.eims.sls_app.dataaccess.Users;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.utils.MyPushTask;
import com.eims.sls_app.utils.NetWork;
import com.eims.sls_app.view.MyToast;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 功能：注册界面，实现注册操作 版本
 *
 * @author Administrator 修改日期：2013-3-11
 */
public class RegisterActivity extends MyBaseActivity implements OnClickListener {
    private Context context = RegisterActivity.this;
    private Button btn_login, btn_reg;
    private ImageButton btn_back;
    private EditText et_name, et_pass, et_upass, et_qqNum;
    private String userName, userPass, userRePass, userqq;
    private String opt, auth, info, time, imei, crc; // 格式化后的参数
    private MyAsynTask myAsynTask;
    private MyHandler myHandler;
    private ProgressDialog mProgress = null;
    private SharedPreferences settings;
    private TextView reg_tip, reg_phone_num_button, tv_passAlert;
    private LinearLayout tv_passSecurityLevel;// 密码安全度判断显示
    private TextView tv_weaK, tv_middle, tv_strong;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_register);
        App.activityS.add(this);
        init();
        findView();
        setListener();
    }

    /**
     * 初始化UI
     */
    private void findView() {
        myHandler = new MyHandler();
        btn_back = (ImageButton) this.findViewById(R.id.btn_back);
        tv_passSecurityLevel = (LinearLayout) this.findViewById(R.id.tv_passSecurityLevel);// 密码安全度显示
        tv_weaK = (TextView) findViewById(R.id.tv_weak);
        tv_middle = (TextView) findViewById(R.id.tv_middle);
        tv_strong = (TextView) findViewById(R.id.tv_strong);
        tv_passSecurityLevel.setVisibility(View.GONE);
        tv_passAlert = (TextView) findViewById(R.id.tv_passAlert);
        tv_passAlert.setVisibility(View.GONE);
        btn_login = (Button) this.findViewById(R.id.reg_top_btn_login);
        btn_reg = (Button) this.findViewById(R.id.reg_btn_reg);
        et_name = (EditText) this.findViewById(R.id.reg_et_userName);
        et_pass = (EditText) this.findViewById(R.id.reg_et_userPass);// 密码
        et_upass = (EditText) this.findViewById(R.id.reg_et_reUserPass);
        et_qqNum = (EditText) findViewById(R.id.reg_et_qqnumber);
        reg_tip = (TextView) findViewById(R.id.reg_tip);
        reg_phone_num_button = (TextView) findViewById(R.id.reg_phone_num_button);
        reg_tip.setText(Html.fromHtml("注册即表示同意" + "<font color='#1a65cb'>《"
//                + getResources().getString(R.string.app_logo)
                + "cp软件用户注册协议》</font>"));
        // 显示下划线
        reg_phone_num_button.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

    /**
     * 初始化参数
     */
    private void init() {
        opt = "1";
        time = RspBodyBaseBean.getTime();
        imei = RspBodyBaseBean.getIMEI(RegisterActivity.this);
    }

    /**
     * 绑定监听
     */
    private void setListener() {
        btn_back.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_reg.setOnClickListener(this);
        // et_name.setOnFocusChangeListener(new
        // MyEditTextFocusChangeListener());
        et_pass.addTextChangedListener(new EditChangedListener());
        // et_upass.setOnFocusChangeListener(new
        // MyEditTextFocusChangeListener());
        reg_tip.setOnClickListener(this);
        reg_phone_num_button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reg_top_btn_login:
                doLogin();
                break;
            case R.id.reg_btn_reg:
                if (NetWork.isConnect(RegisterActivity.this)) {
                    if (check()) {
                        myAsynTask = new MyAsynTask();
                        myAsynTask.execute();
                    }
                } else {
                    MyToast.getToast(RegisterActivity.this, "网络连接异常，注册失败！").show();
                }
                break;
            case R.id.btn_back:
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                RegisterActivity.this.startActivity(intent);
                RegisterActivity.this.finish();
                break;
            case R.id.reg_tip:
                Intent intent2 = new Intent(RegisterActivity.this, Regist_Agreement.class);
                RegisterActivity.this.startActivity(intent2);
                break;
            case R.id.reg_phone_num_button:
                Intent intent1 = new Intent(RegisterActivity.this, Regist_phoneNum_Activity.class);
                RegisterActivity.this.startActivity(intent1);
                RegisterActivity.this.finish();
                break;
        }
    }

    /**
     * 校验用户名和密码
     */
    private boolean check() {
        boolean isTrue = true;
        /**
         * 判断是否含非法字符
         */
        String all = "^[\\u4e00-\\u9fa5\\w]+$";// 匹配中文、数字、字母
        String username = et_name.getText().toString().trim();
        if ("".equals(username)) {
            MyToast.getToast(context, "用户名不能为空").show();
            return false;
        }
        Pattern pattern = Pattern.compile(all);
        boolean isPassUserName = pattern.matcher(username).matches();
        if (!isPassUserName) {
            MyToast.getToast(context, "用户名只能为数字、英文、中文").show();
            return false;
        }

        int charLength = LotteryUtils.getRexStrLength(username);
        if (charLength < 6 || charLength > 16) {
            MyToast.getToast(context, "用户名长度为6-16个字符").show();
            return false;
        }

        /**
         * 验证密码
         */
        String pwd = et_pass.getText().toString();
        if ("".equals(pwd)) {
            MyToast.getToast(context, "请输入密码").show();
            return false;
        }
        if (pwd.length() < 6 || pwd.length() > 16) {
            MyToast.getToast(context, "请输入6-16位数字、字母或常用符号，字母区分大小写").show();
            return false;
        }

        if (quchong(pwd).size() < 3 || !ruoCheck(pwd)) {
            MyToast.getToast(context, "您输入的密码强度过弱，请重新输入，试试字母、数字、常用符号的组合").show();
            return false;
        }
        /**
         * 确认密码
         */
        String pwd1 = et_upass.getText().toString();
        if ("".equals(pwd1)) {
            MyToast.getToast(context, "请输入确认密码").show();
            return false;
        }
        if (!pwd.equals(pwd1)) {
            MyToast.getToast(context, "两次密码输入不一致，请重新输入").show();
            return false;
        }
        String qqNumber = et_qqNum.getText().toString();
        /**
         * 验证qq数字位数
         */
        if (!"".equals(qqNumber)) {
            byte[] bytes = qqNumber.getBytes();
            if (bytes.length < 6) {
                MyToast.getToast(context, "qq号最少为6位").show();
                return false;
            }
        }
        if ("".equals(qqNumber)) {
            MyToast.getToast(context, "请输入qq号").show();
            return false;
        }
        return true;
    }

    /**
     * 检验是否密码强度过弱
     */
    public boolean ruoCheck(String password) {
        if (password.equals("123456") || password.equals("654321") || password.equals("123456789")
                || password.equals("987654321") || password.equals("12345678") || password.equals("87654321")
                || password.equals("1234567") || password.equals("7654321"))
            return false;
        else
            return true;
    }

    /**
     * 是否包含特殊字符
     *
     * @param password
     * @return
     */
    public boolean checkSpecial(String password) {
        String all = "(\\~|\\!|\\@|\\#|\\$|\\%|\\^|\\&|\\*|\\(|\\)|\\_|\\-|\\=|\\+|\\\\|\\||\\[|\\]|\\{|\\}|\\;|\\'|\\:|\\\"|\\,|\\.|\\/|\\<|\\>|\\?)";
        Pattern pattern = Pattern.compile(all, Pattern.CASE_INSENSITIVE);
        boolean isSpecial = pattern.matcher(password).find();
        return isSpecial;
    }

    /**
     * 是否包含数字
     *
     * @param password
     * @return
     */
    public boolean checkContainsNum(String password) {
        String all = "[0-9]";
        Pattern pattern = Pattern.compile(all, Pattern.CASE_INSENSITIVE);
        boolean isSpecial = pattern.matcher(password).find();
        return isSpecial;
    }

    /**
     * 是否包含字母
     *
     * @param password
     * @return
     */
    public boolean checkContainsLetter(String password) {
        String all = "[a-zA-Z]";
        Pattern pattern = Pattern.compile(all, Pattern.CASE_INSENSITIVE);
        boolean isSpecial = pattern.matcher(password).find();
        return isSpecial;
    }

    /**
     * 去除重复字符方法
     */
    public List quchong(String password) {
        List list = new ArrayList();
        for (int i = 0; i < password.length(); i++) {
            if (!list.contains(password.substring(i, i + 1))) {
                list.add(password.substring(i, i + 1));
            }
        }
        return list;
    }

    /**
     * 跳到登录页面
     */
    private void doLogin() {
        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
        RegisterActivity.this.startActivity(intent);
        this.finish();
    }

    /**
     * 改变强度
     *
     * @param tv
     */
    public void changeTextView(TextView tv) {
        tv_weaK.setBackgroundResource(R.drawable.follow_btn_bg);
        tv_middle.setBackgroundResource(R.drawable.follow_btn_bg);
        tv_strong.setBackgroundResource(R.drawable.follow_btn_bg);
        tv_weaK.setTextColor(Color.BLACK);
        tv_middle.setTextColor(Color.BLACK);
        tv_strong.setTextColor(Color.BLACK);

        tv.setBackgroundResource(R.drawable.bet_btn_dan_selected);
        tv.setTextColor(Color.WHITE);
    }

    /**
     * 监听密码文本输入
     */
    class EditChangedListener implements TextWatcher {
        @Override
        public void afterTextChanged(Editable et) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // 输入文本之前的状态
        }

        @Override
        public void onTextChanged(CharSequence et, int start, int count, int after) {
            tv_passAlert.setVisibility(View.GONE);
            // 输入文字中的状态，count是一次性输入字符数
            String str = et.toString();
            if (str.length() < 6 || str.length() > 16) {
                tv_passAlert.setVisibility(View.VISIBLE);
                tv_passAlert.setText("请输入6-16位数字、字母或常用符号，字母区分大小写");
            }

            if (quchong(str).size() < 3 || !ruoCheck(str)) {
                tv_passAlert.setVisibility(View.VISIBLE);
                tv_passAlert.setText("您输入的密码强度过弱，请重新输入，试试字母、数字、常用符号的组合");
            }

            if (null == str || "".equals(str)) {
                tv_passSecurityLevel.setVisibility(View.VISIBLE);
                changeTextView(tv_weaK);

            } else if (str.length() < 6 || quchong(str).size() < 3 || !ruoCheck(str)) {
                tv_passSecurityLevel.setVisibility(View.VISIBLE);
                changeTextView(tv_weaK);
                // 如果密码长度大于等于6 且 去重后密码长度大于等于3 且 密码中包含特殊字符 且 密码中包含英文字符 且 密码中包含数字
                // 的才为强密码。
            } else if (str.length() > 5 && quchong(str).size() > 2 && checkSpecial(str) && checkContainsLetter(str)
                    && checkContainsNum(str)) {
                tv_passSecurityLevel.setVisibility(View.VISIBLE);
                changeTextView(tv_strong);

            } else {
                tv_passSecurityLevel.setVisibility(View.VISIBLE);
                changeTextView(tv_middle);
            }

        }
    }

    // /**
    // * 当文本改变时 *
    // */
    // class MyEditTextFocusChangeListener implements OnFocusChangeListener {
    // @Override
    // public void onFocusChange(View v, boolean hasFocus) {
    // if (!hasFocus) {
    // String str = ((EditText) v).getText().toString();
    // if (null == str){
    // Toast.makeText(RegisterActivity.this,
    // "数据不能为空",Toast.LENGTH_SHORT).show();
    // }else if(str.length()<6||quchong(str).size()<3||!ruoCheck(str)){
    // tv_passAlert.setVisibility(View.VISIBLE);
    // tv_passAlert.setText("密码安全系数：弱");
    // }else if(str.length() >5&&quchong(str).size()>2&&!checkSpecial(str)){
    // tv_passAlert.setVisibility(View.VISIBLE);
    // tv_passAlert.setText("密码安全系数：中");
    // }else{
    // tv_passAlert.setVisibility(View.VISIBLE);
    // tv_passAlert.setText("密码安全系数：强");
    // }
    // }
    // }
    // }

    /**
     * 异步任务 用来后台获取数据
     */
    class MyAsynTask extends AsyncTask<Void, Integer, String> {
        String error = "-1";

        @Override
        protected String doInBackground(Void... params) {
            userName = et_name.getText().toString().trim();
            userPass = et_pass.getText().toString().trim();
            userRePass = et_upass.getText().toString().trim();
            userqq = et_qqNum.getText().toString().trim();
            // if (userName.length() < 1)
            // return "-11";
            // if (userPass.length() < 6)
            // return "-10";
            // String name_verification = "^[\u4e00-\u9fa5_a-zA-Z0-9]{5,16}$";
            // if (!userName.matches(name_verification))
            // return "-12";
            // if (userPass.equals(userRePass)) {
            // 足彩沐沐47
            // 西西43
            // lau12138 52
            // mmm球 51
            // 我来了绝恋 4
            String key = MD5.md5(App.MD5_key);
            info = RspBodyBaseBean.changeRegister_info("0", userName, MD5.md5(userPass + App.MD5_key), "", userqq);
            crc = RspBodyBaseBean.getCrc(time, imei, key, info, "-1");
            auth = RspBodyBaseBean.getAuth(crc, time, imei, "-1");

            String values[] = {opt, auth, info};
            String result = HttpUtils.doPost(App.names, values, App.path);

            Log.i("x", "注册info---------" + info);
            Log.i("x", "注册时的result----" + result);

            if ("-500".equals(result))
                return result;

            System.out.println("注册得到的信息" + result);
            try {
                JSONObject ob = new JSONObject(result);
                error = ob.getString("error");

                if ("0".equals(error)) {
                    App.user = new Users();
                    App.user.setUid(ob.optString("uid"));
                    App.user.setName(ob.optString("name"));
                    App.user.setRealityName(ob.optString("realityName"));
                    App.user.setBalance(ob.optLong("balance"));
                    App.user.setFreeze(ob.optDouble("freeze"));
                    App.user.setEmail(ob.optString("email"));
                    App.user.setIdcardnumber(ob.optString("idcardnumber"));
                    App.user.setMobile(ob.optString("mobile"));
                    App.user.setMsgCount(ob.optInt("msgCount"));
                    App.user.setMsgCountAll(ob.optInt("msgCountAll"));
                    App.user.setScoring(ob.optInt("scoring"));
                    App.user.setCode(ob.optString("code"));
                    Log.e("code",ob.optString("code"));
                    // 用户密码 （没加密的）
                    App.user.setUserPass(userPass);
                    return App.ERROR_SUCCESS + "";
                }
            } catch (Exception e) {
                e.printStackTrace();
                error = "-1";
            }
            // } else {
            // error = "-2";
            // }
            return error;
        }

        /**
         * 最开始执行的
         */
        @Override
        protected void onPreExecute() {
            mProgress = BaseHelper.showProgress(RegisterActivity.this, null, "注册中....", true, false);
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            Log.i("x", "发送消息。。。。。");
            myHandler.sendEmptyMessage(Integer.parseInt(result));
            super.onPostExecute(result);
        }
    }

    /**
     * 重写返回键事件
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            RegisterActivity.this.startActivity(intent);
            RegisterActivity.this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 处理页面显示的
     */
    @SuppressLint("HandlerLeak")
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            mProgress.dismiss();
            switch (msg.what) {
                case 0:
                    MyToast.getToast(RegisterActivity.this, "注册成功").show();
                    App.Status = "1";
                    MyPushTask.newInstances(RegisterActivity.this).commit();
                    // doLogin();
                    RegisterActivity.this.finish();
                    MainActivity.toCenter();

                    // 将用户名记住
                    settings = getSharedPreferences("app_user", 0);
                    Editor editor = settings.edit();
                    editor.putString("name", userName);
                    editor.putString("pass", userPass);
                    editor.putBoolean("isLogin", true);
                    editor.commit();
                    break;
                case 1:
                    MyToast.getToast(RegisterActivity.this, "网络不稳定，请稍后再试").show();
                    break;
                case -2:
                    MyToast.getToast(RegisterActivity.this, "两次密码不正确，请重新输入").show();
                    break;
                case -10:
                    MyToast.getToast(RegisterActivity.this, "密码长度必须大于等于6").show();
                    break;
                case -11:
                    MyToast.getToast(RegisterActivity.this, "用户名不能为空").show();
                    break;
                case -12:
                    MyToast.getToast(RegisterActivity.this, "用户名不符合规则").show();
                    break;
                case -500:
                    MyToast.getToast(RegisterActivity.this, "连接超时").show();
                    break;
                case -110:
                    MyToast.getToast(RegisterActivity.this, "该用户名已存在。注册失败").show();
                    break;
                default:
                    MyToast.getToast(RegisterActivity.this, "注册失败").show();
                    Log.i("x", "-----注册错误-----:" + msg.what);
                    break;
            }
            super.handleMessage(msg);
        }
    }
}
